package pku;

import pku.serializers.OldMessageSerializer;

import java.io.*;
import java.util.HashMap;
//import net.jpountz.lz4.LZ4BlockOutputStream;


public class MessageStore {
    private final String rootPath;
    private HashMap<String, BufferedOutputStream> myFileName;

    public MessageStore(String folderRootPath) {
        rootPath = folderRootPath;
        myFileName = new HashMap<>();
    }

    public void writeToFile(String topicName, DefaultMessage message) {
        if (!myFileName.containsKey(topicName)) {
            createFile(topicName);
        }
        BufferedOutputStream bw = myFileName.get(topicName);
        try {
            bw.write(OldMessageSerializer.message2bytes(message));
//            bw.write(message.toString());
//            bw.newLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void createFile(String folderName) {
        String fileName = Thread.currentThread().getName();

        try {
            File f = new File(rootPath + File.separator + folderName + '_' + fileName);
            FileOutputStream fo = new FileOutputStream(f);
//            LZ4BlockOutputStream zip = new LZ4BlockOutputStream(fo, 16 * 1024);
            //DeflaterOutputStream zip = new DeflaterOutputStream(fo, new Deflater(1, true));
            BufferedOutputStream writer = new BufferedOutputStream(fo, 4096);
            myFileName.put(folderName, writer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    void close() {
        myFileName.forEach((topicName, bw) -> {
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
}
